package com.wavercaz.freeforum.filters;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.wavercaz.freeforum.utils.JWTUtil;
import com.wavercaz.freeforum.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token=request.getHeader("Authorization");
        if(token!=null){
            List<String> abandonTokens = redisTemplate != null?(List<String>) redisTemplate.opsForValue().get("abandonTokens"):null;
            Verification verification = null;
            //检测token是否在黑名单中
            if (abandonTokens != null) {
                for (String v:abandonTokens) {
                    if (v.equals(token)) {
                        ResponseResult res = new ResponseResult(50011,"账号异常，请重新登录");
                        try {
                            response.setStatus(200);
                            response.setContentType("application/json;charset=UTF-8");
                            response.getWriter().print(JSON.toJSONString(res));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return;
                    }
                };
            }
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(decodedJWT.getClaim("authorityId").asString());
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(decodedJWT.getClaim("id").asString(),null,authorities);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
